import React, { memo, useEffect, useState } from 'react'
//antd
import {Upload, Card, Spin} from 'antd';
//style
import {DivWrapper} from './style';
//services
import axios from 'axios';
//redux
import {shallowEqual, useSelector,useDispatch} from 'react-redux';
import {changeAvatar} from '../../store/loginStore/actionCreators';




export default memo(function Profile() {
    //定义状态
    const [isUploading, setIsUploading] = useState(false);
    const [avatarUrl, setAvatarUrl] = useState('');

    //redux
    const user = useSelector(state => state.user, shallowEqual);
    const dispatch = useDispatch();


    useEffect(()=> {
        setAvatarUrl(user.avatar);
        // console.log(avatarUrl);
    },[avatarUrl, user.avatar])

    //让user里面的avatar发生改变然后同步
    const handleUploadAvatar = ({file})=>{
        // console.log(file);
        // console.log(avatarUrl);
        //file就是要想服务端发送的数据
        const data = new FormData();
        data.append('Token',
        'a767b7a743571278d2cbef49302974f602c2bd02:yil9FV7PWiA4Znm3CTSeow9jWX0=:eyJkZWFkbGluZSI6MTYxMjY3Njk0NiwiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzMzMTYwIiwiYWlkIjoiMTc0NTM3NSIsImZyb20iOiJmaWxlIn0=')
        data.append('file', file);
        axios.post('http://up.imgapi.com/',data)
        .then(res => {
            // console.log(res);
            if(res.status === 200){
                setAvatarUrl(res.data.linkurl);
                // console.log(avatarUrl);
                setIsUploading(false);
                dispatch(changeAvatar(res.data.linkurl));
            }else{
                console.log('图片上传错误');
            }
        })  
    }

    return (
        <Card
            title="个人设置"
            bordered={false}  
            style={{height: 640}} 
        >
            <h1>点击头像上传</h1>
            <DivWrapper>
                <Upload
                    showUploadList={false}
                    customRequest={handleUploadAvatar}
                >
                    <Spin 
                        spinning={isUploading}
                    >
                        <img src={avatarUrl} alt="头像" style={{width:100, height: 100}}/>
                    </Spin>
                </Upload>
            </DivWrapper>
        </Card>
    )
    
})
